package com.example.controller;

import com.example.common.RedisCode;
import com.example.config.AuthAccess;
import com.example.until.Result;
import com.google.code.kaptcha.Producer;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpRequest;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @title: KaptchaController
 * @Author wjf
 * @Date: 2022/10/11 9:44
 * @Version 1.0
 */
@RestController
public class KaptchaController {
    private final Producer producer;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    public KaptchaController(Producer producer) {
        this.producer = producer;
    }

    @AuthAccess
    @CrossOrigin
    @GetMapping("/vc.png")
    public Result getVerifyCode(HttpSession session) throws IOException {
        //1.生成验证码
        String code = producer.createText();
//        session.setAttribute("kaptcha", code);   //可以更换成 redis 实现
        stringRedisTemplate.opsForValue().set(RedisCode.IMGCODE,code,1, TimeUnit.MINUTES);  //把验证码放入redis 1分钟后失效
        BufferedImage bi = producer.createImage(code);
        //2.写入内存
        FastByteArrayOutputStream fos = new FastByteArrayOutputStream();
        ImageIO.write(bi, "png", fos);
        //3.生成 base64
        return Result.ok(Base64.encodeBase64String(fos.toByteArray())) ;
    }
}
